package com.zhouxiaoge.thread;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Logger;

/**
 * @author 周小哥  gqzmy@163.com 2022/11/18 15:48
 */

public class ThreadFactory {
    private static final Logger logger = Logger.getLogger(ThreadFactory.class.getName());

    public static ExecutorService createFixedThreadPool(String threadName) {
        AtomicInteger threadNumber = new AtomicInteger(0);
        // 自定义拒绝策略
        // ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
        //         cpuCoreNumber(),
        //         cpuCoreNumber() * 2,
        //         60L,
        //         TimeUnit.SECONDS,
        //         new ArrayBlockingQueue<>(1),
        //         r -> new Thread(r, threadName + "-" + threadNumber.getAndIncrement()),
        //         (r, executor) -> {
        //             try {
        //                 if (!executor.isShutdown()) {
        //                     System.out.println("阻塞加入队列");
        //                     executor.getQueue().put(r);
        //                 }
        //             } catch (Exception exception) {
        //                 logger.warning(exception.getMessage());
        //             }
        //         }
        // );
        // 抛异常
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                cpuCoreNumber(),
                cpuCoreNumber() * 2,
                60L,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(1),
                r -> new Thread(r, threadName + "-" + threadNumber.getAndIncrement()),
                new ThreadPoolExecutor.AbortPolicy()
        );
        return threadPoolExecutor;
    }

    public static int cpuCoreNumber() {
        int i = Runtime.getRuntime().availableProcessors();
        return i <= 0 ? 1 : i;
    }

    public static void main(String[] args) {
        ExecutorService zhouxiagoe = ThreadFactory.createFixedThreadPool("zhouxiagoe");
        for (int i = 0; i < 100; i++) {
            int finalI = i;
            try {
                zhouxiagoe.submit(() -> {
                    System.out.println("--------------------------" + finalI);
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                });
            } catch (Exception exception) {
                logger.warning(exception.getMessage());
            }
        }
        zhouxiagoe.shutdown();
    }
}
